<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="老人姓名" prop="searchElderlyName">
        <el-input
          v-model="queryParams.searchElderlyName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="护理项目" prop="searchProjectName">
        <el-input
          v-model="queryParams.searchProjectName"
          placeholder="请输入护理项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="护理员姓名" prop="searchCaregiverName">
        <el-input
          v-model="queryParams.searchCaregiverName"
          placeholder="请输入护理员姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="期望服务时间" prop="expectedServiceTimeRange">
        <el-date-picker
          v-model="queryParams.expectedServiceTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- Tab切换 -->
    <el-tabs v-model="activeTab" class="mb8" style="margin-top: 20px;">
      <el-tab-pane label="待执行" name="pending"></el-tab-pane>
      <el-tab-pane label="已执行" name="executed"></el-tab-pane>
      <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
    </el-tabs>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="arrangementList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="老人姓名" align="center" prop="elderlyName" />
      <el-table-column label="床位号" align="center" prop="bedNo" />
      <el-table-column label="护理项目名称" align="center" prop="projectName" width="150"/>
      <el-table-column label="项目类型" align="center" prop="projectType" />
      <el-table-column label="护理员姓名" align="center" prop="caregiverName" />
      <el-table-column label="期望服务时间" align="center" prop="expectedServiceTime" width="180">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.expectedServiceTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creatorName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联单据" align="center" prop="relatedOrderNo" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="statusMap[scope.row.status]">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 查看按钮 - 所有状态都可以查看 -->
          <el-button 
            link type="primary" icon="View" 
            @click="handleView(scope.row)"
          >查看</el-button>
          
          <!-- 待执行状态的操作按钮 -->
          <template v-if="scope.row.status === '待执行'">
            <!-- 执行按钮 -->
            <el-button 
              link type="success" icon="Check" 
              @click="handleExecute(scope.row)"
            >执行</el-button>
            
            <!-- 改期按钮 -->
            <el-button 
              link type="warning" icon="Refresh" 
              @click="handleReschedule(scope.row)"
            >改期</el-button>
            
            <!-- 取消按钮 -->
            <el-button 
              link type="danger" icon="Close" 
              @click="handleCancel(scope.row)"
            >取消</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="arrangementRef" :model="form" label-width="100px">
        <el-form-item label="老人姓名">
          <el-input v-model="form.elderlyName" disabled />
        </el-form-item>
        <el-form-item label="床位号">
          <el-input v-model="form.bedNo" disabled />
        </el-form-item>
        <el-form-item label="护理项目名称">
          <el-input v-model="form.projectName" disabled />
        </el-form-item>
        <el-form-item label="项目类型">
          <el-input v-model="form.projectType" disabled />
        </el-form-item>
        <el-form-item label="护理员姓名">
          <el-input v-model="form.caregiverName" disabled />
        </el-form-item>
        <el-form-item label="期望服务时间">
          <el-input v-model="form.expectedServiceTime" disabled />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="form.creatorName" disabled />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="form.createTime" disabled />
        </el-form-item>
        <el-form-item label="关联单据">
          <el-input v-model="form.relatedOrderNo" disabled />
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="form.status" disabled />
        </el-form-item>
        <!-- 已执行状态显示执行记录 -->
        <el-form-item label="执行记录" v-if="form.status === '已执行'">
          <el-input v-model="form.executionRecord" type="textarea" disabled rows="3" />
        </el-form-item>
        <!-- 已取消状态显示取消原因 -->
        <el-form-item label="取消原因" v-if="form.status === '已取消'">
          <el-input v-model="form.cancelReason" type="textarea" disabled rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="open = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 取消任务弹窗 -->
    <el-dialog title="取消任务" v-model="cancelOpen" width="400px" append-to-body>
      <el-form ref="cancelRef" :model="cancelForm" :rules="cancelRules" label-width="100px">
        <el-form-item label="取消原因" prop="reason">
          <el-input 
            v-model="cancelForm.reason" 
            type="textarea" 
            placeholder="请输入取消任务的原因（必填）" 
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitCancel">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 执行任务弹窗 -->
    <el-dialog title="执行任务" v-model="executeOpen" width="500px" append-to-body>
      <el-form ref="executeRef" :model="executeForm" :rules="executeRules" label-width="100px">
        <el-form-item label="执行时间" prop="executionTime">
          <el-date-picker
            v-model="executeForm.executionTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择执行时间"
            :default-time="new Date(2000, 1, 1, 12, 0, 0)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="执行记录" prop="executionRecord">
          <el-input 
            v-model="executeForm.executionRecord" 
            type="textarea" 
            placeholder="请输入执行情况（必填）" 
            rows="3"
          />
        </el-form-item>
        <el-form-item label="执行图片（可选）">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :file-list="uploadFileList"
            :limit="3"
            list-type="picture-card"
            accept="image/jpeg,image/jpg,image/png"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip text-muted">
                支持jpg/png格式，最多上传3张
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="executeOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitExecute">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 改期任务弹窗 -->
    <el-dialog title="任务改期" v-model="rescheduleOpen" width="500px" append-to-body>
      <el-form ref="rescheduleRef" :model="rescheduleForm" :rules="rescheduleRules" label-width="100px">
        <el-form-item label="新服务时间" prop="newTime">
          <el-date-picker
            v-model="rescheduleForm.newTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择新的服务时间（不能早于当前时间）"
            :default-time="new Date(2000, 1, 1, 12, 0, 0)"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
            :disabled-minutes="disabledMinutes"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="改期原因" prop="reason">
          <el-input 
            v-model="rescheduleForm.reason" 
            type="textarea" 
            placeholder="请输入改期原因（必填）" 
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rescheduleOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitReschedule">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TaskArrangement">
import { ref, reactive, toRefs, getCurrentInstance, watch } from 'vue'
import { listArrangement, getArrangement } from "@/api/serve/arrangement"
import { cancelTask, executeTask, rescheduleTask } from "@/api/serve/arrangement"
import { listEnableNursingItems } from "@/api/serve/project"
import { listUser } from "@/api/system/user"
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from "@/utils/auth"
import useUserStore from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const nursingItemList = ref([]);
const caregiverList = ref([]);

// 上传配置
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload")
const uploadHeaders = ref({ Authorization: "Bearer " + getToken() })
const uploadFileList = ref([])

// 自定义时间格式化函数：将时间转为 "年-月-日 时:分" 格式
const formatDateTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1并补零
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 时间格式化函数2：用于API参数（完整格式）
const formatDateTime2 = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 状态标签样式映射
const statusMap = {
  '待执行': 'info',
  '已执行': 'success',
  '已取消': 'danger'
}

// 表格数据与加载状态
const arrangementList = ref([])
const loading = ref(true)
const total = ref(0)
const showSearch = ref(true)  // 控制搜索表单显示

// 弹窗控制
const open = ref(false)                // 查看弹窗
const cancelOpen = ref(false)          // 取消任务弹窗
const executeOpen = ref(false)         // 执行任务弹窗
const rescheduleOpen = ref(false)      // 改期任务弹窗
const title = ref("任务详情")

// Tab切换：初始值为'pending'，与第一个Tab的name一致
const activeTab = ref('pending')

// 表单与查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    searchElderlyName: null,
    searchProjectName: null,
    searchCaregiverName: null,
    expectedServiceTimeRange: [],
    status: '待执行'  // 默认查询待执行
  },
  form: {  // 查看弹窗表单
    id: null,
    elderlyName: null,
    bedNo: null,
    projectName: null,
    projectType: null,
    caregiverName: null,
    expectedServiceTime: null,
    creatorName: null,
    createTime: null,
    relatedOrderNo: null,
    status: null,
    executionRecord: null,
    cancelReason: null
  },
  cancelForm: {  // 取消任务表单
    taskId: null,
    reason: null
  },
  executeForm: {  // 执行任务表单
    taskId: null,
    executionTime: new Date(),  // 默认当前时间
    executionRecord: null,
    executionImage: []  // 存储图片路径
  },
  rescheduleForm: {  // 改期任务表单
    taskId: null,
    newTime: null,
    reason: null
  },
  // 表单验证规则
  cancelRules: {
    reason: [{ required: true, message: '请输入取消原因', trigger: 'blur' },
             { max: 200, message: '原因不能超过200字', trigger: 'blur' }]
  },
  executeRules: {
    executionTime: [{ required: true, message: '请选择执行时间', trigger: 'change' }],
    executionRecord: [{ required: true, message: '请输入执行记录', trigger: 'blur' },
                      { max: 500, message: '记录不能超过500字', trigger: 'blur' }]
  },
  rescheduleRules: {
    newTime: [{ required: true, message: '请选择新服务时间', trigger: 'change' }],
    reason: [{ required: true, message: '请输入改期原因', trigger: 'blur' },
             { max: 200, message: '原因不能超过200字', trigger: 'blur' }]
  }
})

const { 
  queryParams, form, cancelForm, executeForm, rescheduleForm,
  cancelRules, executeRules, rescheduleRules 
} = toRefs(data)

// 初始化：加载关联数据
const initSelectData = () => {
  // 加载启用的护理项目（备用，如需编辑功能）
  listEnableNursingItems({ status: 1 }).then(response => {
    nursingItemList.value = response.rows
  })
  // 加载护理员列表（备用）
  listUser({ role: 'caregiver' }).then(response => {
    caregiverList.value = response.rows
  })
}

// 查询任务列表
const getList = () => {
  loading.value = true
  const params = { ...queryParams.value }

  // 判断是否是管理员（userId=1 或者 角色包含admin）
  const isAdmin = userStore.id == 1 || (userStore.roles && userStore.roles.includes('admin'))

  // 处理时间范围参数 - 需要放在params对象中
  if (params.expectedServiceTimeRange && params.expectedServiceTimeRange.length === 2) {
    params.params = params.params || {}
    params.params.expectedServiceTimeStart = params.expectedServiceTimeRange[0]
    params.params.expectedServiceTimeEnd = params.expectedServiceTimeRange[1]
  } else if (params.status === '待执行' && !isAdmin) {
    // 待执行状态：护理员只显示今天及之前的任务，管理员不受时间限制
    const today = new Date()
    const todayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59)
    params.params = params.params || {}
    params.params.expectedServiceTimeEnd = formatDateTime2(todayEnd)
  }
  delete params.expectedServiceTimeRange 

  // 添加排序参数：按服务时间正序
  params.params = params.params || {}
  params.params.orderByColumn = 'expected_service_time'
  params.params.isAsc = 'asc'

  listArrangement(params).then(response => {
    arrangementList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索按钮触发
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  proxy.resetForm("queryRef")
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10
  // 这里的逻辑和Tab切换保持一致
  queryParams.value.status = activeTab.value === 'pending' ? '待执行' 
    : activeTab.value === 'executed' ? '已执行' : '已取消'
  getList()
}

// 监听 activeTab 的变化，自动更新查询状态
watch(activeTab, (newTab) => {
  queryParams.value.status = newTab === 'pending' ? '待执行'
    : newTab === 'executed' ? '已执行' 
    : '已取消'
  queryParams.value.pageNum = 1
  getList()
})

// 查看任务详情
const handleView = (row) => {
  // 跳转路由到详情页，传递任务ID
  router.push({
    path: '/serve/task/detail',
    query: { id: row.id }
  })
}

// 打开取消任务弹窗
const handleCancel = (row) => {
  cancelForm.value.taskId = row.id
  cancelForm.value.reason = null
  cancelOpen.value = true
}

// 提交取消任务
const submitCancel = () => {
  proxy.$refs["cancelRef"].validate(valid => {
    if (valid) {
      cancelTask(cancelForm.value.taskId, cancelForm.value.reason).then(() => {
        proxy.$modal.msgSuccess("取消成功")
        cancelOpen.value = false
        getList()  // 刷新列表
      }).catch(error => {
        proxy.$modal.msgError(error.msg || "取消失败")
      })
    }
  })
}

// 打开执行任务弹窗
const handleExecute = (row) => {
  executeForm.value.taskId = row.id
  executeForm.value.executionTime = new Date()  // 默认当前时间
  executeForm.value.executionRecord = null
  executeForm.value.executionImage = []  // 清空图片
  uploadFileList.value = []  // 清空上传文件列表
  executeOpen.value = true
}

// 图片上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    // 将上传成功的图片URL添加到数组中
    const imageUrl = response.data || response.url || response.fileName
    if (imageUrl) {
      executeForm.value.executionImage.push(imageUrl)
    }
  } else {
    proxy.$modal.msgError("图片上传失败：" + (response.msg || "未知错误"))
  }
}

// 图片删除回调
const handleUploadRemove = (file, fileList) => {
  // 从数组中移除对应的图片URL
  if (file.response) {
    const imageUrl = file.response.data || file.response.url || file.response.fileName
    const index = executeForm.value.executionImage.indexOf(imageUrl)
    if (index > -1) {
      executeForm.value.executionImage.splice(index, 1)
    }
  }
}

// 提交执行任务
const submitExecute = () => {
  proxy.$refs["executeRef"].validate(valid => {
    if (valid) {
      const executionData = {
        executionTime: executeForm.value.executionTime,
        executionRecord: executeForm.value.executionRecord,
        executionImage: Array.isArray(executeForm.value.executionImage) 
          ? executeForm.value.executionImage.join(',')  // 数组转为字符串
          : executeForm.value.executionImage || ''  // 已经是字符串或为空
      }
      executeTask(executeForm.value.taskId, executionData).then(() => {
        proxy.$modal.msgSuccess("执行成功")
        executeOpen.value = false
        getList()  // 刷新列表
      }).catch(error => {
        proxy.$modal.msgError(error.msg || "执行失败")
      })
    }
  })
}

// 打开改期任务弹窗
const handleReschedule = (row) => {
  rescheduleForm.value.taskId = row.id
  rescheduleForm.value.newTime = null
  rescheduleForm.value.reason = null
  rescheduleOpen.value = true
}

// 提交改期任务
const submitReschedule = () => {
  proxy.$refs["rescheduleRef"].validate(valid => {
    if (valid) {
      const rescheduleData = {
        newExpectedTime: rescheduleForm.value.newTime,
        reason: rescheduleForm.value.reason
      }
      rescheduleTask(rescheduleForm.value.taskId, rescheduleData).then(() => {
        proxy.$modal.msgSuccess("改期成功")
        rescheduleOpen.value = false
        getList()  // 刷新列表
      }).catch(error => {
        proxy.$modal.msgError(error.msg || "改期失败")
      })
    }
  })
}

// 选择项变化（预留批量操作）
const handleSelectionChange = (selection) => {
  // 可添加批量处理逻辑
}

// ========== 改期时间限制：禁止选择过去的时间 ==========
// 禁用今天之前的日期
const disabledDate = (date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date < today
}

// 禁用今天已过的小时（仅当选择的是今天时）
const disabledHours = () => {
  const selectedDate = rescheduleForm.value.newTime
  if (!selectedDate) return []
  
  const selected = new Date(selectedDate)
  const now = new Date()
  
  // 如果选择的是今天，禁用当前小时之前的所有小时
  if (selected.toDateString() === now.toDateString()) {
    const currentHour = now.getHours()
    const disabledHoursList = []
    for (let i = 0; i < currentHour; i++) {
      disabledHoursList.push(i)
    }
    return disabledHoursList
  }
  return []
}

// 禁用今天当前小时已过的分钟（仅当选择的是今天且当前小时时）
const disabledMinutes = (selectedHour) => {
  const selectedDate = rescheduleForm.value.newTime
  if (!selectedDate) return []
  
  const selected = new Date(selectedDate)
  const now = new Date()
  
  // 如果选择的是今天，且选择的小时是当前小时，禁用当前分钟之前的所有分钟
  if (selected.toDateString() === now.toDateString() && selectedHour === now.getHours()) {
    const currentMinute = now.getMinutes()
    const disabledMinutesList = []
    for (let i = 0; i < currentMinute; i++) {
      disabledMinutesList.push(i)
    }
    return disabledMinutesList
  }
  return []
}

// 初始化执行
initSelectData()
getList()
</script>